/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.editors.project;

import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.beans.task.TaskBean;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.entity.GetBaseEntityListCmd;
import cn.easyplatform.studio.cmd.identity.*;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.*;
import cn.easyplatform.studio.web.editors.AbstractPanelEditor;
import cn.easyplatform.studio.web.editors.BandboxCallback;
import cn.easyplatform.studio.web.editors.Editor;
import cn.easyplatform.studio.web.editors.EditorCallback;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import cn.easyplatform.studio.web.views.impl.MenuAccessView;
import org.apache.xpath.operations.Bool;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.DropEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.OpenEvent;
import org.zkoss.zul.*;

import java.util.*;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class RoleEditor extends AbstractPanelEditor {

    private Listbox roleGrid;

    private Textbox key;

    private Textbox name;

    private Textbox desp;

    private Bandbox image;

    private Tree sourceMenus;

    private Listbox targetDesktopMenus;

    private Listbox targetMobileMenus;

    private Tabbox targetMenusTabbox;

    private Combobox typeCombobox;

    private Textbox searchTextbox;

    private Textbox searchMenuTextbox;

    private List<MenuVo> allMenus;

    private RoleVo selectedRole;

    private List<AccessVo> accessVos;

    public RoleEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
    }

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("menu.role"), "~./images/group.png", "~./include/editor/project/role.zul");
        accessVos = StudioApp.execute(new GetAccessInfoCmd());
        for (Component comp : is.getFellows()) {
            if (comp.getId().equals("projectRole_listbox_roles"))
                roleGrid = (Listbox) comp;
            else if (comp.getId().equals("projectRole_textbox_id"))
                key = (Textbox) comp;
            else if (comp.getId().equals("projectRole_textbox_name"))
                name = (Textbox) comp;
            else if (comp.getId().equals("projectRole_textbox_desp"))
                desp = (Textbox) comp;
            else if (comp.getId().equals("projectRole_bandbox_image")) {
                image = (Bandbox) comp;
                comp.addEventListener(Events.ON_OPEN, this);
            } else if (comp.getId().equals("projectRole_tree_sourceMenus")) {
                sourceMenus = (Tree) comp;
            } else if (comp.getId().equals("projectRole_listbox_targetDesktopMenus")) {
                targetDesktopMenus = (Listbox) comp;
                comp.addEventListener(Events.ON_DROP, this);
            } else if (comp.getId().equals("projectRole_listbox_targetMobileMenus")) {
                targetMobileMenus = (Listbox) comp;
                comp.addEventListener(Events.ON_DROP, this);
            } else if (comp.getId().equals("projectRole_tabbox_main")) {
                targetMenusTabbox = (Tabbox) comp;
            } else if (comp.getId().equals("projectRole_button_add") || comp.getId().equals("projectRole_button_delete")
                    || comp.getId().equals("projectRole_button_Edit")) {
                String AuthorizedKey = null;
                if (comp.getId().equals("projectRole_button_add"))
                    AuthorizedKey = "roleAdd";
                else if (comp.getId().equals("projectRole_button_delete"))
                    AuthorizedKey = "roleDelete";
                else if (comp.getId().equals("projectRole_button_Edit"))
                    AuthorizedKey = "roleEdit";
                boolean isAuthorized = Contexts.getUser().isAuthorized(AuthorizedKey);
                if (isAuthorized)
                    comp.addEventListener(Events.ON_CLICK, this);
                else
                    ((Button) comp).setDisabled(true);
            } else if (comp instanceof Image) {
                comp.addEventListener(Events.ON_CLICK, this);
            }/* else if (comp.getId().equals("projectRole_combobox_type")) {
                type = (Combobox) comp;
                type.setValue(Labels.getLabel("device.desktop"));
                type.addEventListener(Events.ON_CHANGE, this);
            } */else if (comp.getId().equals("projectRole_combobox_search_type")) {
                typeCombobox = (Combobox) comp;
                typeCombobox.setValue(Labels.getLabel("button.all"));
                typeCombobox.addEventListener(Events.ON_CHANGE, this);
            } else if (comp.getId().equals("projectRole_textbox_search")) {
                searchTextbox = (Textbox) comp;
                searchTextbox.addEventListener(Events.ON_OK, this);
            } else if (comp.getId().equals("projectRole_textbox_searchMenu")) {
                searchMenuTextbox = (Textbox) comp;
                searchMenuTextbox.addEventListener(Events.ON_OK, this);
            }
        }
        redraw(StudioApp.execute(new GetRolesCmd()));
        allMenus = StudioApp.execute(new GetMenusCmd());
        redrawSourceMenu();
        selectedRole = new RoleVo();
        selectedRole.setCode('C');
    }

    private void redraw(List<RoleVo> roles) {
        roleGrid.getItems().clear();
        for (RoleVo role : roles) {
            Listitem row = new Listitem();
            row.setValue(role);
            row.appendChild(new Listcell(role.getId()));
            /*String typeString;
            if (Strings.isBlank(role.getType()) == false && role.getType().equals("mil")) {
                typeString = Labels.getLabel("device.mobile");
            } else
                typeString = Labels.getLabel("device.desktop");
            row.appendChild(new Listcell(typeString));*/
            row.appendChild(new Listcell(role.getName()));
            row.appendChild(new Listcell(role.getDesp()));
            row.addEventListener(Events.ON_CLICK, this);
            roleGrid.appendChild(row);
        }
    }

    private void redrawSourceMenu() {
        sourceMenus.getTreechildren().getChildren().clear();
        Map<String, Treeitem> map = new HashMap<String, Treeitem>();
        for (MenuVo menu : allMenus) {
            Treeitem parent = map.get(menu.getParentMenuId());
            if (parent == null) {
                parent = new Treeitem();
                parent.setValue(menu);
                Treerow row = new Treerow();
                Treecell cell = new Treecell(menu.getId());
                cell.setParent(row);
                cell = new Treecell(menu.getName());
                cell.setParent(row);
                cell = new Treecell(menu.getDesp());
                cell.setParent(row);
                cell = new Treecell();
                Button showBtn = new Button();
                showBtn.setHflex("1");
                showBtn.setLabel(Labels.getLabel("menu.view"));
                showBtn.addEventListener(Events.ON_CLICK, this);
                showBtn.setParent(cell);
                cell.setParent(row);
                row.setParent(parent);
                parent.setDraggable("menu");
                parent.setParent(sourceMenus.getTreechildren());
                parent.setOpen(false);
                map.put(menu.getId(), parent);
            } else {
                Treeitem ti = new Treeitem();
                ti.setValue(menu);
                Treerow row = new Treerow();
                Treecell cell = new Treecell(menu.getId());
                cell.setParent(row);
                cell = new Treecell(menu.getName());
                cell.setParent(row);
                cell = new Treecell(menu.getDesp());
                cell.setParent(row);
                cell = new Treecell();
                Button showBtn = new Button();
                showBtn.setHflex("1");
                showBtn.setLabel(Labels.getLabel("menu.view"));
                showBtn.addEventListener(Events.ON_CLICK, this);
                showBtn.setParent(cell);
                cell.setParent(row);
                row.setParent(ti);
                Treechildren tc = parent.getTreechildren();
                if (tc == null) {
                    tc = new Treechildren();
                    tc.setParent(parent);
                }
                ti.setDraggable("menu");
                ti.setParent(tc);
                map.put(menu.getId(), ti);
            }
        }
    }

    private void refreshMenus(List<String> selectedItems, Listbox targetMenus) {
        targetMenus.getItems().clear();
        // 目标
        for (String id : selectedItems) {
            for (MenuVo vo : allMenus) {
                if (id.equals(vo.getId())) {
                    targetMenus.appendChild(createItem(vo));
                    break;
                }
            }
        }
    }

    private Listitem createItem(MenuVo vo) {
        Listitem li = new Listitem();
        li.setValue(vo);
        li.appendChild(new Listcell(vo.getId()));
        li.appendChild(new Listcell(vo.getName()));
        li.appendChild(new Listcell(vo.getDesp()));
        Button showBtn = new Button();
        showBtn.setHflex("1");
        showBtn.setLabel(Labels.getLabel("menu.view"));
        showBtn.addEventListener(Events.ON_CLICK, this);
        Listcell cell = new Listcell();
        cell.appendChild(showBtn);
        li.appendChild(cell);
        li.setDraggable("menu");
        li.setDroppable("menu");
        li.addEventListener(Events.ON_DROP, this);
        return li;
    }

    private void setValue() {
        key.setValue(selectedRole.getId());
        /*String typeString;
        if (Strings.isBlank(selectedRole.getType()) == false && selectedRole.getType().equals("mil")) {
            typeString = Labels.getLabel("device.mobile");
        } else
            typeString = Labels.getLabel("device.desktop");
        type.setValue(typeString);*/
        name.setValue(selectedRole.getName());
        desp.setValue(selectedRole.getDesp());
        image.setValue(selectedRole.getImage());
        if (selectedRole.getCode() != 'C') {
            refreshMenus(StudioApp.execute(new GetRoleMenusCmd(selectedRole
                    .getId(), GetRoleMenusCmd.RoleType.DESKTOPTYPE)), targetDesktopMenus);
            refreshMenus(StudioApp.execute(new GetRoleMenusCmd(selectedRole
                    .getId(), GetRoleMenusCmd.RoleType.MOBILETYPE)), targetMobileMenus);
        } else {
            targetDesktopMenus.getItems().clear();
            targetMobileMenus.getItems().clear();
        }
    }

    @Override
    public void dispatch(Event event) {
        if (event.getName().equals(Events.ON_OPEN)) {// actionbox
            if (selectedRole == null) {
                WebUtils.showError(Labels.getLabel("editor.select",
                        new String[]{Labels.getLabel("menu.role")}));
                return;
            }
            AbstractView.createIconView(new BandboxCallback(this, image), "*", event.getTarget())
                    .doOverlapped();
        } else if (event.getName().equals(Events.ON_DROP)) {
            if (selectedRole == null) {
                WebUtils.showError(Labels.getLabel("editor.select",
                        new String[]{Labels.getLabel("menu.role")}));
                return;
            }
            DropEvent de = (DropEvent) event;
            Listbox listbox = targetMenusTabbox.getSelectedIndex() == 0 ? targetDesktopMenus: targetMobileMenus;
            if (de.getDragged() instanceof Treeitem) {// 来自树
                Treeitem ti = (Treeitem) de.getDragged();
                MenuVo vo = ti.getValue();
                for (Listitem item : listbox.getItems()) {
                    MenuVo mv = item.getValue();
                    if (mv.getId().equals(vo.getId())) {
                        WebUtils.showError(Labels
                                .getLabel("editor.menu.exists"));
                        return;
                    }
                }
                if (de.getTarget() instanceof Listbox) {// 加到后面
                    listbox.appendChild(createItem(vo));
                } else {// 加到前面
                    int pos = ((Listitem) de.getTarget()).getIndex();
                    listbox.getItems().add(pos, createItem(vo));
                }
            } else {// 本身
                if (de.getTarget() instanceof Listbox) {
                    de.getDragged().detach();
                    listbox.appendChild(de.getDragged());
                } else {
                    int pos = ((Listitem) de.getTarget()).getIndex();
                    Listitem item = (Listitem) de.getDragged();
                    item.detach();
                    listbox.getItems().add(pos, item);
                }
            }
        } else if (event.getTarget() instanceof Button) {
            if (event.getTarget().getId().equals("projectRole_button_add")) {
                selectedRole = new RoleVo();
                selectedRole.setCode('C');
                key.setReadonly(false);
                setValue();
            } else if (event.getTarget().getId().equals("projectRole_button_delete")) {
                if (selectedRole == null || selectedRole.getCode() == 'C') {
                    WebUtils.showError(Labels.getLabel("editor.select",
                            new String[]{Labels.getLabel("menu.studio.role")}));
                    return;
                }
                WebUtils.showConfirm(Labels.getLabel("button.delete"), this);
            } else if (event.getTarget().getId().equals("projectRole_button_Edit")) {//save
                if (selectedRole == null) {
                    WebUtils.showError(Labels.getLabel("editor.select",
                            new String[]{Labels.getLabel("menu.studio.role")}));
                    return;
                }
                if (Strings.isBlank(key.getValue())) {
                    WebUtils.notEmpty(Labels.getLabel("entity.id"));
                    return;
                }
                if (Strings.isBlank(name.getValue())) {
                    WebUtils.notEmpty(Labels.getLabel("entity.name"));
                    return;
                }
                selectedRole.setId(key.getValue());
                /*if (type.getSelectedItem() != null)
                    selectedRole.setType((String) type.getSelectedItem().getValue());*/
                selectedRole.setDesp(desp.getValue());
                selectedRole.setName(name.getValue());
                selectedRole.setImage(image.getValue());
                List<String> mobileMenus = new ArrayList<String>();
                List<String> desktopMenus = new ArrayList<String>();
                for (Listitem row : targetMobileMenus.getItems()) {
                    MenuVo vo = row.getValue();
                    vo.setType("mil");
                    if (!mobileMenus.contains(vo.getId())) {
                        mobileMenus.add(vo.getId());
                    }

                }
                for (Listitem row : targetDesktopMenus.getItems()) {
                    MenuVo vo = row.getValue();
                    vo.setType("ajax");
                    if (!desktopMenus.contains(vo.getId())) {
                        desktopMenus.add(vo.getId());
                    }
                }
                selectedRole.setMobileMenus(mobileMenus);
                selectedRole.setDeskTopMenus(desktopMenus);
                if (StudioApp.execute(event.getTarget(), new UpdateRoleCmd(
                        selectedRole))) {
                    if (selectedRole.getCode() == 'C') {
                        Listitem row = new Listitem();
                        row.setValue(selectedRole);
                        row.appendChild(new Listcell(selectedRole.getId()));
                        String typeString;
                        /*if (Strings.isBlank(selectedRole.getType()) == false && selectedRole.getType().equals("mil")) {
                            typeString = Labels.getLabel("device.mobile");
                        } else
                            typeString = Labels.getLabel("device.desktop");
                        row.appendChild(new Listcell(typeString));*/
                        row.appendChild(new Listcell(selectedRole.getName()));
                        row.appendChild(new Listcell(selectedRole.getDesp()));
                        row.addEventListener(Events.ON_CLICK, this);
                        roleGrid.appendChild(row);
                        row.setSelected(true);
                    } else {
                        Listitem row = getSelectedRow();
                        List<Listcell> labels = row.getChildren();
                        labels.get(1).setLabel(selectedRole.getName());
                        labels.get(2).setLabel(selectedRole.getDesp());
                    }
                    selectedRole.setCode('U');
                    WebUtils.showSuccess(Labels.getLabel("button.save")
                            + Labels.getLabel("menu.studio.role")
                            + selectedRole.getId());
                }
            } else if (event.getTarget().getParent().getParent().getParent() instanceof Treeitem) {
                Treeitem treeitem = (Treeitem) event.getTarget().getParent().getParent().getParent();
                MenuVo menuVo = treeitem.getValue();
                List<BaseEntity> taskList = new ArrayList<>();
                if (Strings.isBlank(menuVo.getTasks()) == false) {
                    List<String> idList = Arrays.asList(menuVo.getTasks().split(","));
                    taskList = StudioApp.execute(new GetBaseEntityListCmd(idList));
                }
                final List<BaseEntity> finalTaskList = taskList;
                AbstractView.createMenuAccessView(event.getTarget(), accessVos, new EditorCallback<List<BaseEntity>>() {
                    @Override
                    public List<BaseEntity> getValue() {
                        return finalTaskList;
                    }

                    @Override
                    public void setValue(List<BaseEntity> value) {

                    }

                    @Override
                    public String getTitle() {
                        return Labels.getLabel("entity.task");
                    }

                    @Override
                    public Page getPage() {
                        return sourceMenus.getPage();
                    }

                    @Override
                    public Editor getEditor() {
                        return null;
                    }
                }).doOverlapped();
            } else if (event.getTarget().getParent().getParent() instanceof Listitem) {
                if (Strings.isBlank(selectedRole.getId())) {
                    WebUtils.showInfo(Labels.getLabel("editor.select", new Object[] { Labels.getLabel("admin.user.role") }));
                    return;
                }
                final String type =  targetMenusTabbox.getSelectedIndex() == 0 ? "ajax": "mil";
                Listitem listitem = (Listitem) event.getTarget().getParent().getParent();
                MenuVo menuVo = listitem.getValue();
                List<BaseEntity> taskList = new ArrayList<>();
                if (Strings.isBlank(menuVo.getTasks()) == false) {
                    //根据菜单id搜索taskid
                    List<String> idList = Arrays.asList(menuVo.getTasks().split(","));
                    //根据taskId搜索所有的taskbean
                    taskList = StudioApp.execute(new GetBaseEntityListCmd(idList));
                }
                //获取这个功能对应的全部的标示
                List<RoleAccessVo> roleAccessVos = new ArrayList<>();
                for (RoleAccessVo accessVo : selectedRole.getRoleAccessVos()) {
                    for (BaseEntity task: taskList) {
                        if (task.getId().equals(task.getId()) && type.equals(accessVo.getType())) {
                            roleAccessVos.add(accessVo);
                            break;
                        }
                    }
                }
                final List<RoleAccessVo> finalRoleAccessVos = roleAccessVos;
                AbstractView.createRoleAccessView(event.getTarget(), taskList, accessVos,new EditorCallback<List<RoleAccessVo>>() {
                    @Override
                    public List<RoleAccessVo> getValue() {
                        return finalRoleAccessVos;
                    }

                    @Override
                    public void setValue(List<RoleAccessVo> value) {
                        for (RoleAccessVo accessVo : value) {
                            accessVo.setType(type);
                            accessVo.setRoleId(selectedRole.getId());
                        }
                        //替换相同的taskid,type的内容
                        if (selectedRole.getRoleAccessVos() != null) {
                            for (RoleAccessVo addAccessVo : value) {
                                int deleteIndex = -1;
                                for (int index = 0; index < selectedRole.getRoleAccessVos().size(); index++) {
                                    RoleAccessVo currentAccessVo = selectedRole.getRoleAccessVos().get(index);
                                    if (addAccessVo.getTaskId().equals(currentAccessVo.getTaskId()) &&
                                            type.equals(currentAccessVo.getType()) && selectedRole.getId().equals(currentAccessVo.getRoleId())) {
                                        deleteIndex = index;
                                        break;
                                    }
                                }
                                if (deleteIndex > -1) {
                                    selectedRole.getRoleAccessVos().remove(deleteIndex);
                                }
                                selectedRole.getRoleAccessVos().add(addAccessVo);
                            }
                        } else {
                            selectedRole.setRoleAccessVos(value);
                        }
                    }

                    @Override
                    public String getTitle() {
                        return Labels.getLabel("entity.task");
                    }

                    @Override
                    public Page getPage() {
                        return sourceMenus.getPage();
                    }

                    @Override
                    public Editor getEditor() {
                        return null;
                    }
                }).doOverlapped();
            }
        } else if (event.getTarget() instanceof Image) {
            Listbox listbox = targetMenusTabbox.getSelectedIndex() == 0 ? targetDesktopMenus: targetMobileMenus;
            if (selectedRole == null) {
                WebUtils.showError(Labels.getLabel("editor.select",
                        new String[]{Labels.getLabel("menu.studio.role")}));
                return;
            }
            if (event.getTarget().getId().equals("projectRole_image_chooseAllBtn")) {
                List<Treeitem> items = sourceMenus.getTreechildren()
                        .getChildren();
                for (Treeitem ti : items) {
                    MenuVo vo = ti.getValue();
                    listbox.appendChild(createItem(vo));
                }
            } else if (event.getTarget().getId().equals("projectRole_image_chooseBtn")) {
                if (sourceMenus.getSelectedCount() > 0) {
                    for (Treeitem ti : sourceMenus.getSelectedItems()) {
                        MenuVo vo = ti.getValue();
                        listbox.appendChild(createItem(vo));
                    }
                }
            } else if (event.getTarget().getId().equals("projectRole_image_removeBtn")) {
                if (listbox.getSelectedCount() > 0) {
                    List<Component> cs = new ArrayList<Component>();
                    for (Listitem ti : listbox.getSelectedItems())
                        cs.add(ti);
                    for (Component c : cs)
                        c.detach();
                }
            } else if (event.getTarget().getId().equals("projectRole_image_removeAllBtn")) {
                listbox.getItems().clear();
            }
        } else if (event.getTarget() instanceof Listitem) {
            Listitem row = (Listitem) event.getTarget();
            selectedRole = row.getValue();
            selectedRole.setCode('U');
            //根据权限id填入全部的标示
            selectedRole.setRoleAccessVos(StudioApp.execute(new GetRoleAccessInfoCmd(selectedRole.getId())));
            key.setReadonly(true);
            setValue();
        } else if (event.getTarget().equals(searchTextbox)) {
            if (event instanceof OpenEvent) {
                OpenEvent evt = (OpenEvent) event;
                String val = (String) evt.getValue();
                ((Textbox) event.getTarget()).setValue(val);
            }
            search();
        } else if (event.getTarget().equals(typeCombobox)) {
            search();
        } else if (event.getTarget().equals(searchMenuTextbox)) {
            if (event instanceof OpenEvent) {
                OpenEvent evt = (OpenEvent) event;
                String val = (String) evt.getValue();
                ((Textbox) event.getTarget()).setValue(val);
            }
            searchMenu();
        } else if (event.getName().equals(Events.ON_OK)) {
            selectedRole.setCode('D');
            if (StudioApp.execute(new UpdateRoleCmd(selectedRole))) {
                getSelectedRow().detach();
                selectedRole = new RoleVo();
                selectedRole.setCode('C');
                key.setReadonly(false);
                setValue();
            }
        }
    }

    private Listitem getSelectedRow() {
        if (selectedRole == null || selectedRole.getCode() == 'C')
            return null;
        return roleGrid.getSelectedItem();
    }

    private void search() {
        List<RoleVo> roles = StudioApp.execute(new GetRolesCmd());
        String typeString = typeCombobox.getSelectedItem().getValue();
        String searchString = searchTextbox.getValue().trim();
        //点击全部，搜索内容为空
        if (typeString.equals("all") && Strings.isBlank(searchString))
            redraw(roles);
        else {
            List<RoleVo> searchRoles = new ArrayList<>();
            for (RoleVo roleVo: roles) {
                if (Strings.isBlank(searchString)) {
                    searchRoles.add(roleVo);
                    continue;
                }
                else if (roleVo.getId().contains(searchString)) {
                    searchRoles.add(roleVo);
                    continue;
                } else if (roleVo.getName().contains(searchString)) {
                    searchRoles.add(roleVo);
                    continue;
                }
            }
            redraw(searchRoles);
        }
    }

    private void searchMenu() {
        List<MenuVo> allMenuList = StudioApp.execute(new GetMenusCmd());;
        allMenus = new ArrayList<>();
        String searchString = searchMenuTextbox.getValue().trim();
        //点击全部，搜索内容为空
        if (Strings.isBlank(searchString)) {
            allMenus = allMenuList;
            redrawSourceMenu();
        } else {
            for (MenuVo menuVo : allMenuList) {
                if (Strings.isBlank(menuVo.getParentMenuId())) {
                    if (menuVo.getId().contains(searchMenuTextbox.getValue().trim())) {
                        allMenus.add(menuVo);
                        continue;
                    } else if (menuVo.getName().contains(searchMenuTextbox.getValue().trim())) {
                        allMenus.add(menuVo);
                        continue;
                    }
                } else {
                    allMenus.add(menuVo);
                }
            }
            redrawSourceMenu();
        }
    }
}
